/**
 * 项目管理路由
 */
const express = require('express');
const router = express.Router();
const fs = require('fs').promises;
const path = require('path');
const { PROJECTS_DIR } = require('../utils/constants');
const { generateId } = require('../utils/helpers');
const {
    readProjectsIndex,
    saveProjectsIndex,
    readProjectConfig,
    saveProjectConfig,
    getRecycleBinProjects,
    moveToRecycleBin,
    restoreFromRecycleBin,
    permanentlyDeleteProject,
    cleanExpiredRecycleBin
} = require('../services/projectService');

/**
 * 获取所有项目列表
 * GET /api/projects
 */
router.get('/', async (req, res) => {
    try {
        const index = await readProjectsIndex();
        
        // 为每个项目读取完整配置以获取最新的场景信息
        const projectsWithScenes = await Promise.all(
            index.projects.map(async (projectMeta) => {
                try {
                    const config = await readProjectConfig(projectMeta.path);
                    return {
                        ...projectMeta,
                        scenes: config.scenes || [],
                        defaultScene: config.defaultScene,
                        maxConcurrentDownloads: config.maxConcurrentDownloads || 3
                    };
                } catch (error) {
                    console.warn(`⚠️ 读取项目配置失败 (${projectMeta.name}):`, error.message);
                    return {
                        ...projectMeta,
                        scenes: [],
                        defaultScene: null,
                        maxConcurrentDownloads: 3
                    };
                }
            })
        );
        
        res.json({
            success: true,
            data: {
                ...index,
                projects: projectsWithScenes
            }
        });
    } catch (error) {
        console.error('❌ 获取项目列表失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取单个项目详情
 * GET /api/projects/:id
 */
router.get('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 读取完整配置
        const config = await readProjectConfig(projectMeta.path);
        
        res.json({
            success: true,
            data: {
                ...projectMeta,
                ...config
            }
        });
    } catch (error) {
        console.error('❌ 获取项目详情失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 创建新项目
 * POST /api/projects
 * Body: { name, description }
 */
router.post('/', async (req, res) => {
    try {
        const { name, description = '' } = req.body;
        
        if (!name) {
            return res.status(400).json({
                success: false,
                error: '项目名称不能为空'
            });
        }
        
        // 检查重名：读取项目索引
        const index = await readProjectsIndex();
        
        // 检查现有项目是否重名
        const existingProject = index.projects.find(p => p.name === name);
        if (existingProject) {
            console.warn(`⚠️ 项目创建失败：名称 "${name}" 与现有项目重名 (ID: ${existingProject.id})`);
            return res.status(400).json({
                success: false,
                error: `项目名称 "${name}" 已存在于现有项目中，请使用其他名称`
            });
        }
        
        // 检查回收站项目是否重名
        const recycleBinProjects = index.recycleBin || [];
        const recycleBinProject = recycleBinProjects.find(p => p.name === name);
        if (recycleBinProject) {
            console.warn(`⚠️ 项目创建失败：名称 "${name}" 与回收站项目重名 (ID: ${recycleBinProject.id})`);
            return res.status(400).json({
                success: false,
                error: `项目名称 "${name}" 已存在于回收站中，请使用其他名称或先从回收站中彻底删除同名项目`
            });
        }
        
        // 生成项目ID和路径
        const projectId = generateId('project');
        const projectPath = projectId;
        const projectDir = path.join(PROJECTS_DIR, projectPath);
        
        // 创建项目目录、场景目录和模型库目录
        await fs.mkdir(projectDir, { recursive: true });
        const scenesDir = path.join(projectDir, 'scenes');
        await fs.mkdir(scenesDir, { recursive: true });
        
        // 创建模型库目录和配置文件
        const modelsDir = path.join(projectDir, 'models');
        await fs.mkdir(modelsDir, { recursive: true });
        
        // 创建材质库目录
        const materialsDir = path.join(projectDir, 'materials');
        await fs.mkdir(materialsDir, { recursive: true });
        console.log('✅ 材质库目录已创建:', materialsDir);
        
        // 创建贴图目录
        const texturesDir = path.join(projectDir, 'textures');
        await fs.mkdir(texturesDir, { recursive: true });
        console.log('✅ 贴图目录已创建:', texturesDir);
        
        // 生成默认场景ID
        const defaultSceneId = generateId('scene');
        
        // 创建默认场景元数据
        const defaultSceneMetadata = {
            id: defaultSceneId,
            name: '默认场景',
            type: 'GroundScene',
            description: '包含一个默认地面的场景',
            icon: '🏞️',
            sceneFile: `scenes/${defaultSceneId}/config.json`,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        
        // 创建默认场景完整数据
        const defaultSceneData = {
            id: defaultSceneId,
            name: '默认场景',
            type: 'GroundScene',
            description: '包含一个默认地面的场景',
            objects: [],
            lights: [
                {
                    type: 'AmbientLight',
                    color: 0xffffff,
                    intensity: 0.5
                },
                {
                    type: 'DirectionalLight',
                    color: 0xffffff,
                    intensity: 0.8,
                    position: [10, 10, 5],
                    castShadow: true
                }
            ],
            camera: {
                position: [8, 6, 8],
                target: [0, 0, 0]
            },
            settings: {
                showAxes: false,
                showGrid: true,
                backgroundColor: 0x87ceeb
            },
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        
        // 创建场景文件夹和配置文件
        const sceneDir = path.join(scenesDir, defaultSceneId);
        await fs.mkdir(sceneDir, { recursive: true });
        const sceneFilePath = path.join(sceneDir, 'config.json');
        await fs.writeFile(sceneFilePath, JSON.stringify(defaultSceneData, null, 2), 'utf-8');
        
        // 创建空的场景树配置文件
        const treeFilePath = path.join(sceneDir, 'tree.json');
        const emptyTreeData = {
            root: {
                id: 'root',
                name: 'Scene Root',
                type: 'root',
                visible: true,
                locked: false,
                userData: {},
                children: [
                    {
                        id: generateId('node'),
                        name: 'Main Camera',
                        type: 'camera',
                        visible: true,
                        locked: false,
                        userData: {},
                        components: [
                            {
                                type: 'transform',
                                position: { x: 0, y: 5, z: 10 },
                                rotation: { x: -0.5, y: 0, z: 0 },
                                scale: { x: 1, y: 1, z: 1 }
                            },
                            {
                                type: 'camera',
                                cameraType: 'PerspectiveCamera',
                                fov: 50,
                                near: 0.1,
                                far: 1000
                            }
                        ],
                        children: []
                    }
                ]
            },
            nodeCount: 2,
            exportedAt: new Date().toISOString()
        };
        await fs.writeFile(treeFilePath, JSON.stringify(emptyTreeData, null, 2), 'utf-8');
        console.log('✅ 场景树配置文件已创建:', treeFilePath);
        
        // 创建项目配置
        const projectConfig = {
            name: name,
            description: description,
            maxConcurrentDownloads: 3, // 默认批量下载并发数
            scenes: [defaultSceneMetadata],
            defaultScene: defaultSceneId,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        
        // 保存项目配置文件
        await saveProjectConfig(projectPath, projectConfig);
        
        console.log('✅ 默认场景文件已创建:', sceneFilePath);
        
        // 创建 README
        const readme = `# ${name}\n\n${description}\n\n创建时间：${new Date().toLocaleString('zh-CN')}\n`;
        await fs.writeFile(path.join(projectDir, 'README.md'), readme, 'utf-8');
        
        // 更新项目索引（已在前面读取，这里直接使用）
        const projectMeta = {
            id: projectId,
            name: name,
            description: description,
            path: projectPath,
            configFile: `projects/${projectPath}/project.json`,
            isDefault: index.projects.length === 0,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        
        index.projects.push(projectMeta);
        
        // 如果是第一个项目，设为默认
        if (index.projects.length === 1) {
            index.defaultProject = projectId;
        }
        
        await saveProjectsIndex(index);
        
        console.log('✅ 项目创建成功:', name);
        res.json({
            success: true,
            data: {
                ...projectMeta,
                ...projectConfig
            }
        });
        
    } catch (error) {
        console.error('❌ 创建项目失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 更新项目（重命名、修改描述等）
 * PUT /api/projects/:id
 * Body: { name?, description?, maxConcurrentDownloads? }
 */
router.put('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { name, description, maxConcurrentDownloads } = req.body;
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        // 读取项目配置
        const config = await readProjectConfig(projectMeta.path);
        
        // 更新字段
        if (name !== undefined) {
            projectMeta.name = name;
            config.name = name;
        }
        
        if (description !== undefined) {
            projectMeta.description = description;
            config.description = description;
        }
        
        if (maxConcurrentDownloads !== undefined) {
            // 验证范围 1-20
            const value = parseInt(maxConcurrentDownloads, 10);
            if (value >= 1 && value <= 20) {
                config.maxConcurrentDownloads = value;
                console.log(`🔄 批量下载并发数更新为: ${value}`);
            } else {
                console.warn(`⚠️ 无效的并发数值 (${maxConcurrentDownloads})，忽略更新`);
            }
        }
        
        projectMeta.updatedAt = new Date().toISOString();
        config.updatedAt = new Date().toISOString();
        
        // 保存更改
        await saveProjectConfig(projectMeta.path, config);
        await saveProjectsIndex(index);
        
        console.log('✅ 项目更新成功:', name || projectMeta.name);
        res.json({
            success: true,
            data: {
                ...projectMeta,
                ...config
            }
        });
        
    } catch (error) {
        console.error('❌ 更新项目失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 删除项目（移入回收站）
 * DELETE /api/projects/:id
 */
router.delete('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        
        const project = await moveToRecycleBin(id);
        
        console.log('🗑️ 项目已移入回收站:', project.name);
        res.json({
            success: true,
            message: '项目已移入回收站，30天后将自动删除',
            data: project
        });
        
    } catch (error) {
        console.error('❌ 移入回收站失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 设置默认项目
 * POST /api/projects/:id/set-default
 */
router.post('/:id/set-default', async (req, res) => {
    try {
        const { id } = req.params;
        
        const index = await readProjectsIndex();
        const project = index.projects.find(p => p.id === id);
        
        if (!project) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        index.defaultProject = id;
        await saveProjectsIndex(index);
        
        console.log('✅ 默认项目已设置:', project.name);
        res.json({
            success: true,
            message: '默认项目设置成功'
        });
        
    } catch (error) {
        console.error('❌ 设置默认项目失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取回收站项目列表
 * GET /api/projects/recycle-bin/list
 */
router.get('/recycle-bin/list', async (req, res) => {
    try {
        const recycleBinProjects = await getRecycleBinProjects();
        
        // 计算每个项目距离彻底删除的剩余天数
        const projectsWithDaysLeft = recycleBinProjects.map(project => {
            const deletedDate = new Date(project.deletedAt);
            const now = new Date();
            const daysPassed = Math.floor((now - deletedDate) / (1000 * 60 * 60 * 24));
            const daysLeft = Math.max(0, 30 - daysPassed);
            
            return {
                ...project,
                daysLeft,
                daysPassed
            };
        });
        
        res.json({
            success: true,
            data: projectsWithDaysLeft
        });
    } catch (error) {
        console.error('❌ 获取回收站列表失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 从回收站恢复项目
 * POST /api/projects/recycle-bin/:id/restore
 */
router.post('/recycle-bin/:id/restore', async (req, res) => {
    try {
        const { id } = req.params;
        
        const project = await restoreFromRecycleBin(id);
        
        console.log('♻️ 项目已从回收站恢复:', project.name);
        res.json({
            success: true,
            message: '项目已成功恢复',
            data: project
        });
        
    } catch (error) {
        console.error('❌ 恢复项目失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 从回收站彻底删除项目
 * DELETE /api/projects/recycle-bin/:id
 */
router.delete('/recycle-bin/:id', async (req, res) => {
    try {
        const { id } = req.params;
        
        const project = await permanentlyDeleteProject(id);
        
        console.log('🗑️ 项目已彻底删除:', project.name);
        res.json({
            success: true,
            message: '项目已彻底删除',
            data: project
        });
        
    } catch (error) {
        console.error('❌ 彻底删除项目失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 清空回收站（彻底删除所有项目）
 * POST /api/projects/recycle-bin/clear
 */
router.post('/recycle-bin/clear', async (req, res) => {
    try {
        const recycleBinProjects = await getRecycleBinProjects();
        const deletedProjects = [];
        
        for (const project of recycleBinProjects) {
            try {
                await permanentlyDeleteProject(project.id);
                deletedProjects.push(project);
            } catch (error) {
                console.error(`❌ 删除项目失败 (${project.name}):`, error);
            }
        }
        
        console.log(`🗑️ 回收站已清空，共删除 ${deletedProjects.length} 个项目`);
        res.json({
            success: true,
            message: `回收站已清空，共删除 ${deletedProjects.length} 个项目`,
            data: {
                count: deletedProjects.length,
                projects: deletedProjects
            }
        });
        
    } catch (error) {
        console.error('❌ 清空回收站失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 手动清理过期项目（30天前）
 * POST /api/projects/recycle-bin/clean-expired
 */
router.post('/recycle-bin/clean-expired', async (req, res) => {
    try {
        const result = await cleanExpiredRecycleBin();
        
        console.log(`🧹 已清理 ${result.cleaned} 个过期项目`);
        res.json({
            success: true,
            message: `已清理 ${result.cleaned} 个过期项目`,
            data: result
        });
        
    } catch (error) {
        console.error('❌ 清理过期项目失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

module.exports = router;

